<template>
<div class="page">
    <div class="flex">
        <div class="flex-1">
            <input type="text" v-model="title" name="title" class="px-2 py-2 border font-medium w-full border-gray-300 shadow focus:outline-none focus:shadow-outline" autocomplete="off" @keyup.enter="save" />
        </div>
        <div>
            <div class="px-6 py-2 font-medium border border-gray-300 bg-slate-50 cursor-pointer shadow focus:outline-none focus:shadow-outline hover:bg-slate-100 transition duration-300 ease-in-out" @click="save">Submit</div>
        </div>
    </div>
    <div class="my-4">
        <ul>
            <li class="w-full my-4 flex" v-for="(item, idx) in data" :key="idx">
            <span :class="item.done ? 'line-through italic text-gray-400 cursor-pointer flex-1' : 'cursor-pointer flex-1'" @click="update(item)">{{idx + 1}}. {{item.title}} <span v-if="item.done"> ({{formatTime(item.utime)}}) </span></span>
            <div class="flex items-center">
                <input type="checkbox" @click="done(item)" :checked="item.done" class="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded" />
                <span class="mx-2">
                    <div @click="del(item)" class="cursor-pointer text-xs ml-1 flex-none px-1 py-py-[0.1125rem]  font-medium text-slate-700 ring-1 ring-slate-700/10 hover:bg-slate-50">{{delText}}</div>
                </span>
            </div>
            </li>
        </ul>
    </div>
</div>
</template>

<script lang="ts">
import { defineComponent, ref, Ref, reactive } from 'vue'
import { invoke } from '@tauri-apps/api'
import { ask } from '@tauri-apps/api/dialog';

interface Item  {
    id: string,
    title: string,
    done: boolean,
    ctime: number,
    utime: number,
};

const data: Ref<Item[]> = ref([]);

const key = "todoList";

export default defineComponent({
    setup() {
        const title = ref('');

        const delText = decodeURI('%E2%9C%96');

        const getItem = (id: string) => {
            const tempList = data.value
            for (let index in tempList) {
                if (tempList[index].id === id) {
                    return tempList[index]
                }
            }
        }

        const updateItem = reactive<Item>({
            id: '',
            title: '',
            done: false,
            ctime: 0,
            utime: 0,
        });


        const resetUpdateItem = () => {
            updateItem.id = '';
            updateItem.title = '';
            updateItem.done = false;
            updateItem.ctime = 0;
            updateItem.utime = 0;
        };


        const save_data = () => {
            const data_str = JSON.stringify(data.value);
            invoke('save_data', { contents: data_str })
            .then((response) => {
                console.log(response)
            })
        };

        const save = () => {
            if (title.value === '' || title.value.trim().length == 0) {
                return;
            }
            if (updateItem.title === '') {
                data.value.push({
                    id: Date.now() + "",
                    title: title.value,
                    done: false,
                    ctime: Date.now(),
                    utime: 0,
                });
            } else {
                const item = getItem(updateItem.id) as Item;
                item.title = title.value;
                resetUpdateItem();
            }
            title.value = '';
            save_data();
            // const data_str = JSON.stringify(data.value);
            // localStorage.setItem(key, data_str);
        };

        const done = (item: Item) => {
            item.done = !item.done;
            item.utime = Date.now();
            save_data();
            // localStorage.setItem(key, JSON.stringify(data.value));
        };

        const update  = (item: Item) => {
            title.value = item.title;
            updateItem.id = item.id;
            updateItem.title = item.title;
            updateItem.done = item.done;
            updateItem.ctime = item.ctime;
            updateItem.utime = item.utime;
        };


        const del  = (item: Item) => {
            ask('删除 `' + item.title + '` ?').then((respnse) => {
                if (respnse) {
                    let index = -1;
                    data.value.forEach((record, idx) => {
                        if (record.id === item.id) {
                            index = idx
                            return;
                        }
                    })

                    if (index > -1) {
                        data.value.splice(index, 1);
                        title.value = '';
                        resetUpdateItem();
                        save_data();
                        // localStorage.setItem(key, JSON.stringify(data.value));
                    }
                }
            });
            
        };


        const formatTime = (timestamp: number) => {
            const date = new Date(timestamp);
            const Y = date.getFullYear() + '-';
            const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth()+1) : date.getMonth() +1 ) + '-';
            const D = date.getDate() + ' ';
            const h = date.getHours() + '-';
            const m = date.getMinutes() + '-';
            const s = date.getSeconds();
            // return Y + M + D + h + m + s;
            return Y + M + D;
        }


        // const loadData = () => {
        //     const data = localStorage.getItem(key);
        //     if (data) {
        //         data.value = JSON.parse(data);
        //     }
        // };

        const loadData = () => {
            invoke('load_data')
            .then((response) => {
                data.value = JSON.parse(response as string);
            })
        };

        loadData();

        return {
            save,
            title,
            data,
            done,
            update,
            formatTime,
            delText,
            del,
        }
    },
})
</script>

<style scoped>
.page {
    padding: 30px;
}
</style>
